//
//  WBComposeViewController.swift
//  DXWeibo
//
//  Created by dx on 17/1/21.
//  Copyright © 2017年 dx. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 撰写微博控制器
/**
 加载视图控制器的时候，如果 xib 和控制器同名，默认的构造函数，会优先加载 xib
 */
class WBComposeViewController: UIViewController {

    /// 文本编辑视图
    @IBOutlet weak var textView: WBComposeTextView!
    /// 底部工具栏
    @IBOutlet weak var toolbar: UIToolbar!
    
    /// 发布按钮
    @IBOutlet var sendButton: UIButton!
    
    /// 标题标签 - 换行热键 option + 回车
    @IBOutlet var titleLabel: UILabel!
    
    /// 底部工具栏底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
    ///  表情输入视图
    lazy var emoticonView: CZEmoticonInputView = CZEmoticonInputView.emoticonInputView { [weak self] (emoticon) in
        
        self?.textView.insertEmoticon(em: emoticon)
    }
    
    // MARK: - 视图生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        // 强行更新约束
//        view.layoutIfNeeded()
        
        setupUI()
        
        // 监听键盘通知 - UIWindow
        /**
         参数
         1. 监听对象
         2. 监听方法
         3. 监听的通知字符串
         4. 发送通知的对象，如果是 nil，监听所有的对象
         */
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // 一上来就激活键盘
    override func viewWillAppear(_ animated: Bool) {
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        textView.resignFirstResponder()
    }
    
    // MARK: - 键盘监听方法
    @objc private func keyboardChanged(n: Notification) {
        
        // 1. 目标 rect
        guard let rect = (n.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue)?.cgRectValue,
            let duration = (n.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? NSNumber)?.doubleValue else {
                return
        }
        
        // 2. 设置约束
        let offset = view.bounds.height - rect.origin.y
        toolbarBottomCons.constant = offset
        
        // 3. 动画更新视图
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    @objc fileprivate func close() {
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: - 按钮监听方法
    /// 发布微博
    @IBAction func postStatus() {
        
        // 1. 获取发送给服务器的字符串
        let text = textView.emoticonText
        
        // 2. 发布微博
        // FIXME: - 测试带图片的微博
        let image: UIImage? = UIImage(named: "icon_small_kangaroo_loading_1")
        
        WBNetworkManager.shared.postStatus(text: text, image: image) { (result, isSuccess) in
            
            // 修改指示器样式
            SVProgressHUD.setDefaultStyle(.dark)
            
            let message = isSuccess ? "发布成功" : "网络不给力"
            
            SVProgressHUD.showInfo(withStatus: message)
            
            // 成功处理
            if isSuccess {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    
                    // 恢复样式
                    SVProgressHUD.setDefaultStyle(.light)
                    self.close()
                }
            }
        }
    }
    
    /// 切换表情键盘
    @objc fileprivate func emoticonKeyboard() {
        // textView.inputView 就是文本框的输入视图，系统键盘为 nil
        
        // 测试键盘视图 - 宽度可以随意指定，就是屏幕的宽度
//        let keyboardWindow = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 253))
//        keyboardWindow.backgroundColor = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
        
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil
        
        // 切换键盘必须刷新输入视图
        textView.reloadInputViews()
    }
}

/**
 通知：一对多，只要有注册的监听者，在注销之前，都可以接收到通知！
 代理：一对一，最后设置的代理对象有效！本质上是一个指针！
 
 苹果日常开发中，代理的监听方式是最多的！
 
 - 代理是发生事件时，直接让代理执行方法！效率更高 - 直接的反向传值
 - 通知是发生事件时，将通知发送给通知中心，通知中心再广播通知！效率较低 - 如果层次嵌套非常深时使用
 */
// MARK: - UITextViewDelegate
extension WBComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText
    }
}

// MARK: - 设置界面
private extension WBComposeViewController {
    
    func setupUI() {
        
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        setupNavigationBar()
        setupToolbar()
    }
    
    func setupToolbar() {
        
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        var items = [UIBarButtonItem]()
        
        for s in itemSettings {
            
            guard let imageName = s["imageName"] else {
                continue
            }
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            
            let btn = UIButton()
            btn.setImage(image, for: .normal)
            btn.setImage(imageHL, for: .highlighted)
            btn.sizeToFit()
            
            // 判断 actionName
            if let actionName = s["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            items.append(UIBarButtonItem(customView: btn))
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.titleView = titleLabel
        
        sendButton.isEnabled = false
    }
}


